package com.merry.filedemo.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author zouyb
 */
@RestController
public class UploadController {


    /**
     * 分片上传
     */
    @RequestMapping("/upload")
    public void upload(HttpServletRequest request, HttpServletResponse response){

        //当前分片数
        Integer chunk = null;
        //总分片数
        Integer totalChunk = null;
        String name = null;
        String uploadPath = "F:\\fileItem";

        try(BufferedInputStream os = new BufferedInputStream(null)){
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024);
            factory.setRepository(new File(uploadPath));
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(10 * 1024 * 1024 * 1024);
            upload.setSizeMax(20 * 1024 * 1024 * 1024);
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                if(item.isFormField()){
                    if("chunk".equalsIgnoreCase(item.getFieldName())){
                        //获取当前分片数
                        chunk = Integer.parseInt(item.getString("utf-8"));
                    }
                    if("totalchunk".equalsIgnoreCase(item.getFieldName())){
                        //获取总分片数
                        totalChunk = Integer.parseInt(item.getString("utf-8"));
                    }
                    if("name".equalsIgnoreCase(item.getFieldName())){
                        //获取文件名字
                        name = (item.getString("utf-8"));
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
